import { _decorator, Component, Node } from 'cc';
import DatasSpace from './DatasSpace';
const { ccclass, property } = _decorator;


const CountTime = 5 * 60;
const MaxTili = 3;
@ccclass('TiliMgr')
export class TiliMgr {

  public static _instance: TiliMgr = null
  public static get Instance() {
    if (null == this._instance) {
      this._instance = new TiliMgr();
    }
    return this._instance;
  }

  private lastTiliLocalTime: number = 0;

  private tiliCountTime: number = 0;

  private _isCountTime: boolean = false;

  private countTimeId: any = null;
  init() {
    this.initLocalTili();
  }

  initLocalTili() {
    let _dataStr = localStorage.getItem("tiliCountTime");
    if (_dataStr != null && _dataStr != 'NaN') {
      this.tiliCountTime = Number(_dataStr);
      let lastLoginTime = DatasSpace.Instance.loginTime;
      let nowTime = Date.now();
      let descTime = nowTime - lastLoginTime;
      const addTili = Math.floor(descTime / 60 / 1000);

      if (addTili > 0) {
        if ((addTili + DatasSpace.Instance.ftNum) >= MaxTili) {
          this.addTili(MaxTili - DatasSpace.Instance.ftNum)
        } else {
          this.addTili(addTili)
        }
      }
      if (this.tiliCountTime) {
        this.startCountTime();
      }
      //this.addTili(addTili)
    }
  }

  useTili() {
    DatasSpace.Instance.ftNum -= 1;
    DatasSpace.Instance.setFtNum();

    if (DatasSpace.Instance.ftNum < MaxTili) {
      this.tiliCountTime += CountTime;
      localStorage.setItem("tiliCountTime", this.tiliCountTime.toString());
      this.startCountTime();
    }
  }

  addTili(num: number = 1) {
    if (num < 0) return;
    DatasSpace.Instance.ftNum += num;
    DatasSpace.Instance.setFtNum();
    if (DatasSpace.Instance.ftNum >= MaxTili) {
      this.clearCountTime();
    }
  }

  startCountTime() {
    if (this._isCountTime) return;
    this.countTimeId = setInterval(() => {
      this.tiliCountTime -= 1;
      const SecTime = this.tiliCountTime % 60;
      localStorage.setItem("tiliCountTime", this.tiliCountTime.toString());
      if (SecTime == 0) {
        this.addTili();
      }
    }, 1000)

    this._isCountTime = true;
  }

  clearCountTime() {
    localStorage.setItem("tiliCountTime", null);
    clearInterval(this.countTimeId);
    this._isCountTime = false;
    this.tiliCountTime = 0;
  }
}


